<template>
    <div class="timetable-container">
        <!-- 班级选择部分 -->
        <div class="class-select" v-if="!isStudent">
            <div class="select-info">
                <el-tag size="large" type="info">
                    所选班级：{{ getSelectedClassName() }}
                </el-tag>
            </div>
            <div class="select-filter">
                <el-tag size="large" type="primary">
                    年级：
                </el-tag>
                <el-tree-select v-model="selectedGlobalDeptId" :data="enabledDeptOptions"
                    :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="选择年级"
                    check-strictly default-expand-all style="width: 240px;" />
                <el-tag size="large" type="primary">
                    班级：
                </el-tag>
                <el-select v-model="selectedGlobalClassId" placeholder="选择班级" clearable style="width: 240px;">
                    <el-option v-for="item in allClassData" :key="item.postId" :label="item.postName"
                        :value="item.postId" />
                </el-select>
            </div>
        </div>

        <!-- 出勤率统计卡片 -->
        <el-card shadow="hover" class="chart-card">
            <div class="card-header">
                <div class="title">
                    <el-icon>
                        <TrendCharts />
                    </el-icon>
                    班级出勤率统计
                </div>
                <div class="tabs">
                    <el-radio-group v-model="attendanceChartPeriod" size="small">
                        <el-radio-button value="week">本周</el-radio-button>
                        <el-radio-button value="month">本月</el-radio-button>
                    </el-radio-group>
                </div>
            </div>
            <div ref="attendanceLineChart" class="chart-container"></div>
        </el-card>


        <!-- 学科出勤率统计 -->
        <el-card shadow="hover" class="chart-card">
            <div class="card-header">
                <div class="title">
                    <el-icon>
                        <Collection />
                    </el-icon>
                    各科出勤率统计
                </div>
                <div class="filter-container">
                    <el-radio-group v-model="subjectChartPeriod" size="small" class="filter-item radio-group-inline">
                        <el-radio-button value="today">今日</el-radio-button>
                        <el-radio-button value="week">本周</el-radio-button>
                        <el-radio-button value="month">本月</el-radio-button>
                        <el-radio-button value="quarter">本季度</el-radio-button>
                        <el-radio-button value="semester">本学期</el-radio-button>
                    </el-radio-group>
                </div>
            </div>
            <div ref="subjectBarChart" class="chart-container"></div>
        </el-card>

        <!-- 课程表卡片 -->
        <el-card shadow="hover" class="timetable-card">
            <div class="card-header">
                <div class="title">
                    <el-icon>
                        <Calendar />
                    </el-icon>
                    课程时间表
                </div>
                <div class="actions">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd"
                        v-hasPermi="['manage:course:add']">新增</el-button>
                    <el-button type="warning" plain icon="Download" @click="handleExport"
                        v-hasPermi="['manage:course:export']">导出</el-button>
                </div>
            </div>

            <!-- 课程表 -->
            <div class="timetable-wrapper">
                <div class="timetable">
                    <!-- 表头 - 星期 -->
                    <div class="timetable-row header-row">
                        <div class="timetable-cell period-cell">节次/日期</div>
                        <div v-for="day in weekDays" :key="day.value" class="timetable-cell day-cell">
                            {{ day.label }}
                            <div class="day-date">{{ getDayDate(day.value) }}</div>
                        </div>
                    </div>

                    <!-- 课程内容 -->
                    <div v-for="period in classPeriods" :key="period.id" class="timetable-row">
                        <div class="timetable-cell period-cell">
                            <div class="period-name">第{{ period.id }}节</div>
                            <div class="period-time">{{ period.startTime }}-{{ period.endTime }}</div>
                        </div>

                        <!-- 每天的课程 -->
                        <div v-for="day in weekDays" :key="`${period.id}-${day.value}`"
                            class="timetable-cell course-cell"
                            :class="{ 'has-course': getCourseByPeriodAndDay(period.id, day.value) }">
                            <template v-if="getCourseByPeriodAndDay(period.id, day.value)">
                                <div class="course-content"
                                    @click="handleUpdate(getCourseByPeriodAndDay(period.id, day.value))">
                                    <div class="course-subject">
                                        {{ getSubjectName(getCourseByPeriodAndDay(period.id, day.value).subjectId) }}
                                    </div>
                                    <div class="course-teacher">
                                        {{ getCourseByPeriodAndDay(period.id, day.value).teacher.nickName }}
                                    </div>
                                    <div class="course-actions">
                                        <el-button link type="primary" size="small"
                                            @click.stop="handleDelete(getCourseByPeriodAndDay(period.id, day.value))"
                                            v-hasPermi="['manage:course:remove']">
                                            删除
                                        </el-button>
                                    </div>
                                </div>
                            </template>
                            <template v-else>
                                <div class="no-course">无课</div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>

        <!-- 添加或修改课程管理对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="courseRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="年级" prop="deptId">
                    <el-tree-select v-model="form.deptId" :data="enabledDeptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                        placeholder="请选择归属年级" check-strictly default-expand-all />
                </el-form-item>
                <el-form-item label="班级" prop="postId">
                    <el-select v-model="form.postId" placeholder="请选择班级" clearable>
                        <el-option v-for="item in allClassData" :key="item.postId" :label="item.postName"
                            :value="item.postId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="星期" prop="dayOfWeek">
                    <el-select v-model="form.dayOfWeek" placeholder="请选择星期">
                        <el-option v-for="dict in week_number" :key="dict.value" :label="dict.label"
                            :value="parseInt(dict.value)"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课次" prop="classOrder">
                    <el-select v-model="form.classOrder" placeholder="请选择课次">
                        <el-option v-for="period in classPeriods" :key="period.id"
                            :label="`第${period.id}节 (${period.startTime}-${period.endTime})`"
                            :value="period.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-time-picker clearable v-model="form.startTime" value-format="HH:mm" format="HH:mm"
                        placeholder="请选择开始时间">
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-time-picker clearable v-model="form.endTime" value-format="HH:mm" format="HH:mm"
                        placeholder="请选择结束时间">
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="学科" prop="subjectId">
                    <el-select v-model="form.subjectId" placeholder="请选择学科" clearable>
                        <el-option v-for="item in subjectIdList" :key="item.subjectId" :label="item.subjectName"
                            :value="item.subjectId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="教师" prop="teacherId">
                    <el-select v-model="form.teacherId" placeholder="请选择教师" clearable>
                        <el-option v-for="item in teacherList" :key="item.userId" :label="item.nickName"
                            :value="item.userId" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="StudentManageClassOverview">
import { ref, reactive, toRefs, getCurrentInstance, onMounted, onUnmounted, computed, nextTick, watch } from 'vue';
import { useRoute } from 'vue-router';
import useUserStore from '@/store/modules/user'
import { allCourse, getCourse, delCourse, addCourse, updateCourse, allClass, allSubject } from "@/api/manage/course";
import { deptTreeSelect, allTeacher, allStudent } from "@/api/system/user";
import { getDaysAttendanceRate, getDaysAttendanceRateByType } from "@/api/manage/attendance";
import { getDaysByOption } from "@/utils/lastDays";
import * as echarts from 'echarts';
import { Calendar, TrendCharts } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const { week_number } = proxy.useDict('week_number');


// 获取路由参数
const route = useRoute();

const userStore = useUserStore();
const isStudent = userStore.roles[0] === 'student' ? true : false; // 判断是否是学生角色
const studentInfo = ref(null);

// 课程列表数据
const courseList = ref([]);
const open = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");

// 课程节次定义
const classPeriods = ref([
    { id: 1, name: '第一节', startTime: '08:00', endTime: '08:45' },
    { id: 2, name: '第二节', startTime: '09:00', endTime: '09:45' },
    { id: 3, name: '第三节', startTime: '10:00', endTime: '10:45' },
    { id: 4, name: '第四节', startTime: '11:00', endTime: '11:45' },
    { id: 5, name: '第五节', startTime: '13:30', endTime: '14:15' },
    { id: 6, name: '第六节', startTime: '14:30', endTime: '15:15' },
    { id: 7, name: '第七节', startTime: '15:30', endTime: '16:15' },
    { id: 8, name: '第八节', startTime: '16:30', endTime: '17:15' }
]);

// 星期几
const weekDays = computed(() => {
    const defaultWeekDays = [
        { label: '星期一', value: '1' },
        { label: '星期二', value: '2' },
        { label: '星期三', value: '3' },
        { label: '星期四', value: '4' },
        { label: '星期五', value: '5' },
        { label: '星期六', value: '6' },
        { label: '星期日', value: '7' }
    ];
    return week_number.value
        ? week_number.value.sort((a, b) => a.value - b.value) // 按 value 排序
        : defaultWeekDays;
});

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 100, // 增大页面大小以获取所有课程
    },
    rules: {
        deptId: [
            { required: true, message: "年级不能为空", trigger: "blur" }
        ],
        postId: [
            { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        dayOfWeek: [
            { required: true, message: "星期不能为空", trigger: "change" }
        ],
        classOrder: [
            { required: true, message: "课次不能为空", trigger: "blur" }
        ],
        startTime: [
            { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
            { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        subjectId: [
            { required: true, message: "学科不能为空", trigger: "blur" }
        ],
        teacherId: [
            { required: true, message: "教师不能为空", trigger: "blur" }
        ],
    }
});

const { queryParams, form, rules } = toRefs(data);

// 全局年级以及班级的选择
const allClassData = ref([]);
const enabledDeptOptions = ref([]);
const selectedGlobalDeptId = ref('');
const selectedGlobalClassId = ref('');

// 学科下拉框数据
const subjectIdList = ref([]);
// 教师下拉框数据
const teacherList = ref([]);

// 图表数据
const campusAttendanceRate = ref({});

// 出勤率图表
const attendanceChartPeriod = ref('week');
const attendanceLineChart = ref(null);
let attendanceChart = null;
const subjectChartPeriod = ref('today');
const subjectBarChart = ref(null);
let subjectChart = null;


/** 查询课程管理列表 */
function getList() {
    loading.value = true;
    // 使用全局选择的年级和班级作为查询条件
    const params = {
        deptId: selectedGlobalDeptId.value,
        postId: selectedGlobalClassId.value
    };

    allCourse(params).then(response => {
        courseList.value = response.data;
        loading.value = false;
    });
}

// 班级下拉框数据，获取所有班级
function getAllClass() {
    allClass().then(response => {
        allClassData.value = response.data;
        if (isStudent) {
            selectedGlobalClassId.value = studentInfo.value.postIds[0];
            return;
        } else if (route.query.deptId == selectedGlobalDeptId.value &&
            route.query.classId) {
            selectedGlobalClassId.value = route.query.classId;
            return;
        }
        // 如果有班级数据，默认选择第一个班级
        if (allClassData.value && allClassData.value.length > 0) {
            selectedGlobalClassId.value = allClassData.value[0].postId;
        }
    });
}

// 获取学生信息
function getStudentInfo(studentId) {
    return new Promise((resolve, reject) => {
        allStudent({
            userId: studentId
        }).then(response => {
            if (response.rows && response.rows.length > 0) {
                studentInfo.value = response.rows[0];
                resolve(); // 成功时调用 resolve
            } else {
                console.error('没有找到学生信息');
                reject('没有找到学生信息'); // 失败时调用 reject
            }
        }).catch(error => {
            console.error(error);
            reject(error); // 捕获错误并调用 reject
        });
    });
}

// 获取学科数据
function getAllSubject() {
    allSubject().then(response => {
        subjectIdList.value = response.data;
    });
}

// 获取教师数据
function getAllTeacher() {
    allTeacher().then(response => {
        teacherList.value = response.rows;
    });
}

/** 查询年级下拉树结构 */
function getDeptTree() {
    deptTreeSelect().then(response => {
        enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
        if (isStudent) {
            selectedGlobalDeptId.value = studentInfo.value.deptId;
            selectedGlobalClassId.value = studentInfo.value.postIds[0];
            return;
        } else if (route.query.deptId && route.query.classId) {
            selectedGlobalDeptId.value = route.query.deptId;
            return;
        }
        // 默认选择第一个年级
        if (enabledDeptOptions.value && enabledDeptOptions.value.length > 0) {
            selectedGlobalDeptId.value = 233;
        }
    });
}

/** 过滤禁用的年级 */
function filterDisabledDept(deptList) {
    return deptList.filter(dept => {
        if (dept.disabled) {
            return false;
        }
        if (dept.id == 101) {
            return false;
        }
        if (dept.children && dept.children.length) {
            dept.children = filterDisabledDept(dept.children);
        }
        return true;
    });
}

// 树形结构中查找指定ID的节点
function findDeptById(tree, id) {
    for (const node of tree) {
        if (node.id === id) {
            return node; // 找到目标节点，直接返回
        }
        if (node.children && node.children.length > 0) {
            const result = findDeptById(node.children, id); // 递归查找子节点
            if (result) {
                return result; // 如果在子节点中找到，返回结果
            }
        }
    }
    return null; // 如果未找到，返回 null
}

// 获取选中班级的名称
function getSelectedClassName() {
    if (!selectedGlobalDeptId.value) {
        return '请选择年级';
    }
    if (!selectedGlobalClassId.value) {
        return '请选择班级';
    }

    // 获得当前所选年级，enabledDeptOptions是树形结构，不能直接循环找到
    const selectedDept = findDeptById(enabledDeptOptions.value, selectedGlobalDeptId.value);
    if (!selectedDept) {
        return '未知年级';
    }

    const selectedClass = allClassData.value.find(item => item.postId === selectedGlobalClassId.value);
    if (!selectedClass) {
        return '未知班级';
    }

    // 将班级名称和年级名称拼接
    if (selectedDept.label && selectedClass.postName) {
        return `${selectedDept.label}${selectedClass.postName}`;
    }

    return '未知班级';
}

// 根据课次和星期获取课程
function getCourseByPeriodAndDay(periodId, dayOfWeek) {
    return courseList.value.find(course =>
        course.classOrder == periodId &&
        course.dayOfWeek == dayOfWeek
    );
}

// 获取学科名称
function getSubjectName(subjectId) {
    const subject = subjectIdList.value.find(item => item.subjectId === subjectId);
    return subject ? subject.subjectName : '未知';
}

// 获取教师名称
function getTeacherName(teacherId) {
    const teacher = teacherList.value.find(item => item.userId === teacherId);
    return teacher ? teacher.nickName : '未知';
}

// 获取日期显示
function getDayDate(dayOfWeek) {
    const today = new Date();
    const currentDay = today.getDay() || 7; // 转换为1-7，周日为7
    const diff = dayOfWeek - 1; // 固定从星期一开始计算
    const targetDate = new Date(today);
    targetDate.setDate(today.getDate() - currentDay + diff + 1); // 调整为从星期一开始
    return `${targetDate.getMonth() + 1}/${targetDate.getDate()}`;
}

/** 搜索按钮操作 */
function handleQuery() {
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    selectedGlobalDeptId.value = enabledDeptOptions.value.length > 0 ? enabledDeptOptions.value[0].id : '';
    selectedGlobalClassId.value = allClassData.value.length > 0 ? allClassData.value[0].postId : '';
    handleQuery();
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        courseId: null,
        deptId: selectedGlobalDeptId.value,
        postId: selectedGlobalClassId.value,
        dayOfWeek: null,
        classOrder: null,
        startTime: null,
        endTime: null,
        subjectId: null,
        teacherId: null,
        createTime: null,
        updateTime: null
    };
    proxy.resetForm("courseRef");
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加课程";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _courseId = row.courseId || ids.value;
    getCourse(_courseId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改课程";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["courseRef"].validate(valid => {
        if (valid) {
            if (form.value.courseId != null) {
                updateCourse(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addCourse(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _courseIds = row.courseId || ids.value;
    proxy.$modal.confirm('是否确认删除课程编号为"' + _courseIds + '"的数据项？').then(function () {
        return delCourse(_courseIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('manage/course/export', {
        deptId: selectedGlobalDeptId.value,
        postId: selectedGlobalClassId.value
    }, `course_${new Date().getTime()}.xlsx`)
}

// 获取学科考勤率数据
function getSubjectAttendanceRate(option) {
    if (!selectedGlobalDeptId.value && !selectedGlobalClassId) return;

    const params = {
        "days": getDaysByOption(option),
        "deptId": selectedGlobalDeptId.value,
        "postId": selectedGlobalClassId.value,
        "type": 'subject'
    };

    getDaysAttendanceRateByType(params).then(res => {
        if (res.code === 200) {
            initSubjectBarChart(res.data);
        } else {
            proxy.$message.error('获取学科考勤率数据失败');
        }
    }).catch(err => {
        console.error(err);
        proxy.$message.error('获取学科考勤率数据失败');
    });
}

// 初始化学科出勤率柱状图
function initSubjectBarChart(data) {
    if (!subjectBarChart.value) return;

    if (!data) return;

    // 使用API返回的数据
    const mockData = {
        subjects: data.nameList,
        rates: data.rateList
    };

    // 如果图表已经存在，销毁它
    if (subjectChart) {
        subjectChart.dispose();
    }

    // 创建新图表
    subjectChart = echarts.init(subjectBarChart.value);

    const option = {
        backgroundColor: '#fff',
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                return params[0].name + '<br/>' + params[0].marker + '出勤率: ' + params[0].value + '%';
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '16%', // 增加顶部边距，避免数据标签被遮挡
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: mockData.subjects,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisLabel: {
                color: '#666'
            }
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 100,
            axisLine: {
                show: false
            },
            axisLabel: {
                color: '#666',
                formatter: '{value}%'
            },
            splitLine: {
                lineStyle: {
                    color: '#eee'
                }
            }
        },
        series: [
            {
                name: '出勤率',
                type: 'bar',
                barWidth: '40%',
                itemStyle: {
                    color: '#4080ff'
                },
                data: mockData.rates
            }
        ]
    };

    subjectChart.setOption(option);

    // 添加点击事件
    subjectChart.on('click', function (params) {
        // 显示当前学科的出勤率
        proxy.$message.info(`${params.name}出勤率: ${params.value}%`);
    });
}


// 获取本today、week、month、quarter、semester学校的考勤数据
function getAttendanceRateByOption(option) {
    if (!selectedGlobalDeptId.value && !selectedGlobalClassId) return;
    getDaysAttendanceRate({
        "days": getDaysByOption(option),
        "deptId": selectedGlobalDeptId.value,
        "postId": selectedGlobalClassId.value
    }).then(res => {
        if (res.code === 200) {
            campusAttendanceRate.value = res.data;

            // 更新图表数据
            if (option === attendanceChartPeriod.value) {
                initAttendanceLineChart();
            }
        } else {
            proxy.$message.error('获取图表考勤数据失败');
        }
    }).catch(err => {
        console.error(err);
        proxy.$message.error('获取图表考勤数据失败');
    });
}

// 初始化出勤率折线图
function initAttendanceLineChart() {
    if (!attendanceLineChart.value) return;

    // 应该使用campusAttendanceRate
    const mockData = {
        dates: campusAttendanceRate.value.dateList || [],
        rates: campusAttendanceRate.value.ratesList || []
    };

    // 如果图表已经存在，销毁它
    if (attendanceChart) {
        attendanceChart.dispose();
    }

    // 创建新图表
    attendanceChart = echarts.init(attendanceLineChart.value);

    const option = {
        backgroundColor: '#fff',
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                return params[0].name + '<br/>' + params[0].marker + '出勤率: ' + params[0].value + '%';
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '16%', // 增加顶部边距，避免数据标签被遮挡
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: mockData.dates,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisLabel: {
                color: '#666'
            }
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 100,
            axisLine: {
                show: false
            },
            axisLabel: {
                color: '#666',
                formatter: '{value}%'
            },
            splitLine: {
                lineStyle: {
                    color: '#eee'
                }
            }
        },
        series: [
            {
                name: '出勤率',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 8,
                itemStyle: {
                    color: '#4080ff'
                },
                lineStyle: {
                    color: '#4080ff',
                    width: 3
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(64, 128, 255, 0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(64, 128, 255, 0.1)'
                        }
                    ])
                },
                data: mockData.rates,
                markPoint: {
                    data: [
                        { type: 'max', name: '最大值' },
                        { type: 'min', name: '最小值' }
                    ]
                }
            }
        ]
    };

    attendanceChart.setOption(option);

    // 添加点击事件
    attendanceChart.on('click', function (params) {
        // 显示当天的出勤率
        proxy.$message.info(`${params.name}日出勤率: ${params.value}%`);
    });
}

// 监听全局年级变化
watch(selectedGlobalDeptId, (newVal) => {
    // 当年级变化时，重置班级选择
    if (isStudent) {
        selectedGlobalDeptId.value = studentInfo.value.deptId;
        selectedGlobalClassId.value = studentInfo.value.postIds[0];
    } else if (route.query.deptId == newVal && route.query.classId) {
        selectedGlobalClassId.value = route.query.classId;
    } else if (allClassData.value && allClassData.value.length > 0) {
        selectedGlobalClassId.value = allClassData.value[0].postId;
    }
    // 更新课程表和图表
    getList();
    getAttendanceRateByOption(attendanceChartPeriod.value);
    getSubjectAttendanceRate(subjectChartPeriod.value);
});

// 监听全局班级变化
watch(selectedGlobalClassId, (newVal) => {
    // 更新课程表和图表
    getList();
    getAttendanceRateByOption(attendanceChartPeriod.value);
    getSubjectAttendanceRate(subjectChartPeriod.value);
});

// 监听图表周期变化
watch(attendanceChartPeriod, (newVal) => {
    getAttendanceRateByOption(newVal);
});

watch(subjectChartPeriod, (newVal) => {
    getSubjectAttendanceRate(newVal);
});

onMounted(async () => {
    if (isStudent) {
        try {
            await getStudentInfo(userStore.id); // 等待 getStudentInfo 执行完成
        } catch (error) {
            console.error('获取学生信息失败:', error);
        }
    }
    // 将route.query的deptId、classId都转为数字
    if (route.query.deptId && route.query.classId) {
        route.query.deptId = parseInt(route.query.deptId);
        route.query.classId = parseInt(route.query.classId);
    }

    // 获取基础数据
    getDeptTree();
    getAllClass();
    getAllSubject();
    getAllTeacher();


    // 初始化图表
    nextTick(() => {
        getAttendanceRateByOption('week');
        getAttendanceRateByOption('month');
        getSubjectAttendanceRate('today');

        // 监听窗口大小变化，重绘图表
        window.addEventListener('resize', () => {
            // 重新绘制图表前检查图表实例是否存在
            if (attendanceChart) {
                attendanceChart.resize();
            }
            if (subjectChart) {
                subjectChart.resize();
            }
        });
    });
});

// 组件卸载时清理
onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', () => { });

    // 销毁图表实例前检查是否存在
    if (attendanceChart) {
        attendanceChart.dispose();
    }
    if (subjectChart) {
        subjectChart.dispose();
    }
});
</script>

<style scoped>
.timetable-container {
    padding: 20px;
}

/* 班级选择样式 */
.class-select {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background-color: #fff;
}

.class-select:hover {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 鼠标悬停时显示阴影 */
}

.select-info {
    display: flex;
    align-items: center;
    margin-left: 10px;
    font-weight: bold;
}

.select-filter {
    display: flex;
    gap: 10px;
    align-items: center;
}

.filter-item {
    height: 32px;
    margin-left: 10px;
}

.radio-group-inline {
    display: flex;
    flex-wrap: nowrap;
}


/* 课程表卡片样式 */
.timetable-card,
.chart-card {
    margin-bottom: 20px;
    border-radius: 8px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.card-header .title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    display: flex;
    align-items: center;
}

.card-header .title .el-icon {
    margin-right: 5px;
}

.timetable-wrapper {
    background-color: #fff;
    border-radius: 4px;
    overflow: auto;
}

.timetable {
    width: 100%;
    border-collapse: collapse;
    display: table;
}

.timetable-row {
    display: flex;
    border-bottom: 1px solid #ebeef5;
}

.timetable-row:last-child {
    border-bottom: none;
}

.timetable-cell {
    flex: 1;
    padding: 12px;
    text-align: center;
    border-right: 1px solid #ebeef5;
    min-height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.timetable-cell:last-child {
    border-right: none;
}

.header-row {
    background-color: #f5f7fa;
    font-weight: bold;
}

.period-cell {
    flex: 0 0 120px;
    background-color: #f5f7fa;
}

.day-cell {
    position: relative;
}

.day-date {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.period-name {
    font-weight: bold;
    margin-bottom: 4px;
}

.period-time {
    font-size: 12px;
    color: #909399;
}

.course-cell {
    position: relative;
    cursor: pointer;
    transition: all 0.3s;
}

.course-cell:hover {
    background-color: #f5f7fa;
}

.course-content {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.course-subject {
    font-weight: bold;
    color: #409EFF;
    margin-bottom: 4px;
}

.course-teacher {
    font-size: 12px;
    color: #606266;
    margin-bottom: 4px;
}

.course-actions {
    margin-top: 4px;
    opacity: 0;
    transition: opacity 0.3s;
}

.course-cell:hover .course-actions {
    opacity: 1;
}

.no-course {
    color: #c0c4cc;
    font-size: 12px;
}

.has-course {
    background-color: rgba(64, 158, 255, 0.1);
}

/* 图表容器样式 - 从原有class.vue中复制 */
.chart-container {
    height: 300px;
    width: 100%;
}
</style>